
<template lang="pug">
  .page
    .search-form.mb-10.pl-10.pr-10
      Row(type="flex" justify="start")
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 客户名称：
          Input(v-model="name" placeholder="请输入" clearable)
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 客户所属：
          .choose-saler
            Tooltip(placement="bottom" max-width="200" :disabled="!tipIsShow" theme="light")
              Input.input(v-model="dolderNames" type="text" readonly clearable @on-clear="salersClear")
              div(slot="content")
                .font-14 {{dolderNames}}
            .button(@click="chooseSaler") 选择
          //- Input(v-model="salerName" placeholder="请输入" clearable)
        //- Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
        //-   span.label-txt.w80 企业性质：
        //-   Select(v-model="character"  placeholder="请选择" clearable)
        //-     Option(v-for="(item, index) in characterArr" :value="item.key" :key="index") {{ item.value }}
        //- Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
        //-   span.label-txt.w80 企业规模：
        //-   Select(v-model="size"  placeholder="请选择" clearable)
        //-     Option(v-for="(item, index) in sizeArr" :value="item.key" :key="index") {{ item.value }}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 所属行业：
          Select(v-model="businessType"  placeholder="请选择" clearable)
            Option(v-for="(item, index) in customerBusinesstype_arr" :value="item.key" :key="index") {{ item.value }}
        //- Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
        //-   span.label-txt.w80 注册资本：
        //-   Input(type="number" v-model="registerCapital" clearable)
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 状态：
          RadioGroup.beautiful-radio-group(type="button" v-model="status")
            Radio(label="1") 正常
            Radio(label="2") 关闭
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 新建时间：
          DatePicker(:value="xinjianshijian" type="daterange" placement="bottom" placeholder="请选择日期范围" separator="至" @on-change="timeChange")
          Button.ml-15(type="info" @click="searchBtn") 查询
    .pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(width="100%" :loading="loading" stripe :columns="setThead" :data="listData" @on-selection-change="tableSelectChange")
        div(slot="header")
          .pull-left.table-title-lefttxt
            span.leftText
              | 商务机会数:
              span.text-info.pl-5.pr-5.font-weight {{codeTotal}}
            Divider(type="vertical")
            span.leftText
              | 商务机会转化率:
              span.text-info.pl-5.pr-5.font-weight {{transRate}}%
          .pull-right.table-title-btns
            Button(v-if="hasExportBargain" type="info" @click="exportBtn") 导出
        template(slot-scope="{ row, index }" slot="customerName")
          .u-d-info(@click="gotoDetail(row.customerId)") {{row.customerName}}
        template(slot-scope="{ row, index }" slot="communicate")
          Button.mr-5(type="info" size="small" @click="addCommunication(row.customerId)") 添加
          Button.mr-5(type="info" size="small" @click="checkCommunication(row.customerId)") 查看
        template(slot-scope="{ row, index }" slot="action")
          Button.mr-5(v-if="HRDC_PostSalesContract" type="text" size="small" @click="openCreateModal(row.customerId,row.requirementId,row.brief)") 添加签约合同
          //- Button.mr-5(v-if="!row.isClosed && HRDC_CloseRequirement" type="text" size="small" @click="closeRequirement(row.requirementId)") 关闭
          Button.mr-5(v-if="!row.isClosed && HRDC_CloseRequirement" type="text" size="small" @click="handleShowCloseModal(row)") 关闭
        .clearfix.pl-20.pr-20(slot="footer")
          Page(:total="codeTotal" :current="PageIndex" :page-size="PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
    Modal(v-model="createModal" title="签约")
      Form(ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="130")
        FormItem.mb-5(label="签约需求：")
          span {{requirementName}}
        FormItem.mb-5(label="签约时间：" prop="signTime")
          DatePicker(v-model="formValidate.signTime" type="date" placeholder="请选择" style="display: block" @on-change="signTimeChange")
        FormItem.mb-5(label="签约金额：" prop="amt")
          Input(v-model="formValidate.amt" placeholder="请输入")
        //- FormItem.mb-5(label="合同编号：")
        //-   Input(v-model="formValidate.code" placeholder="请输入")
        FormItem.mb-5(label="签约合同：")
          div
            Upload(:before-upload="createHandleUpload" multiple ref="addUpload" :show-upload-list="true" action="" style="display:inline-block" :headers="headers")
              Button(type="info" icon="ios-cloud-upload-outline" style="width:200px") 点击上传
            span.ml-10(v-show="hasFile" style="color:#ed4014") 请选择方案附件
          template(v-for="(item, index) in fileArr")
            .my-tag.mr-20
              .my-tag-inner {{item.name}}
              .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteFile(index)")
        FormItem.mb-5(label="合同开始时间：" prop="startDate")
          DatePicker(v-model="formValidate.startDate" type="date" placeholder="请选择" style="display: block" @on-change="startDateChange")
        FormItem.mb-5(label="合同结束时间：" prop="endDate")
          DatePicker(v-model="formValidate.endDate" type="date" placeholder="请选择" style="display: block" @on-change="endDateChange")
        FormItem.mb-5(label="合同年限：" prop="duration")
          Input(v-model="formValidate.duration" placeholder="请输入")
        FormItem.mb-5(label="开票金额：" prop="invoiceAmt")
          Input(v-model="formValidate.invoiceAmt" placeholder="请输入")
        FormItem.mb-5(label="开票时间：" prop="invoiceTime")
          DatePicker(v-model="formValidate.invoiceTime" type="date" placeholder="请选择" style="display: block" @on-change="invoiceTimeChange")
        FormItem(label="完成时间：" prop="completeTime")
          DatePicker(:value="formValidate.completeTime" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="请选择" style="display:block" @on-change="completeTimeChange")
        FormItem.mb-5
          Button(icon="ios-cloud-download-outline" @click="") 项目合同模板下载
      template(slot="footer")
        Button(type="info" @click="handleSubmit('formValidate')") 提交
        Button(@click="reviseModal = false") 取消
    createCommunication(ref="createCommunication" :customerId="customerId" :contact_arr="contact_arr" :communicationtype="communicationtype")
    checkCommunication(ref="checkCommunication" :customerId="customerId" :communicationList="communicationList" :communicationTotal="communicationTotal" @get-list="getCommunicationList")
    visibvleTreeList(ref="treeModal" :treeData="treeData" @on-change="getSalerId")
    CloseModal(ref="CloseModal" @query="getList")
</template>

<script>
import HRDCCustomerApi from '@/api/HRDCCustomer.api.js'
import Mixin from '../saleMixin.js'
import createCommunication from '@/view/oti-center/HRDC-common/communication/create.vue'
import checkCommunication from '@/view/oti-center/HRDC-common/communication/check.vue'
import Cookies from 'js-cookie'
import CloseModal from '../close.vue'

export default {
  name: 'hrdc-demand-C',
  data () {
    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      transRate: 0, // 转化率
      name: '',
      salerName: '',
      character: '', // 企业性质
      size: '', // 企业规模
      businessType: '', // 所属行业
      registerCapital: '', // 注册资本
      requirementId: '', // 需求id
      requirementName: '', // 需求名称
      fileArr: [], // 合同附件
      hasFile: false,
      thead: ['selection', 'requirementCode', 'brief', 'customerName', 'hz_price', 'hz_content', 'hz_challenge', 'createrName', 'status', 'businessTypeName', 'closedReason', 'closedByName', 'createTime', 'communicate', 'action'],
      listData: [],
      loading: false,
      codeTotal: 0,
      PageIndex: 1,
      PageSize: 10,
      status: '1',
      createModal: false,
      xinjianshijian: [], // 新建时间
      formValidate: {
        signTime: '', // 签约时间
        amt: '', // 金额
        // code: '', // 合同编号
        startDate: '', // 开始时间
        endDate: '', // 结束时间
        duration: '', // 合同年限
        invoiceAmt: '', // 开票金额
        invoiceTime: '', // 开票时间
        completeTime: this.$moment(new Date()).format('YYYY-MM-DD HH:mm')
      },
      ruleValidate: {
        signTime: [
          { required: true, message: '签约时间不能为空', trigger: 'change' }
        ],
        amt: [
          { required: true, message: '签约金额不能为空', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '开始时间不能为空', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '结束时间不能为空', trigger: 'change' }
        ],
        duration: [
          { required: true, message: '合同年限不能为空', trigger: 'blur' }
        ],
        invoiceAmt: [
          { required: true, message: '开票金额不能为空', trigger: 'blur' }
        ],
        invoiceTime: [
          { required: true, message: '开票时间不能为空', trigger: 'change' }
        ],
        completeTime: [
          { required: true, message: '完成时间不能为空', trigger: 'change' }
        ]
      }
    }
  },
  mixins: [Mixin],
  components: {
    createCommunication,
    checkCommunication,
    CloseModal
  },
  computed: {
    setThead () {
      return this.getTableColumns(this.thead)
    },
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 添加或修改销售合同
    HRDC_PostSalesContract () {
      return this.actionArr.indexOf('HRDC_PostSalesContract') > -1
    },
    // 关闭
    HRDC_CloseRequirement () {
      return this.actionArr.indexOf('HRDC_CloseRequirement') > -1
    },
    // 导出
    hasExportBargain () {
      return this.actionArr.indexOf('ExportBargain') > -1
    },
  },
  created () {
    this.getList()
  },
  watch: {
    $route (to, from) {
      if (to.name === 'hrdc-demand-C') {
        this.getList()
      }
    }
  },
  methods: {
    // 获取列表数据
    getList () {
      this.loading = true
      HRDCCustomerApi.GetBargainItems({
        name: this.name,
        salerName: this.salerName,
        HolderIds: this.salesIds,
        Character: this.character,
        Size: this.size,
        status: this.status,
        BusinessType: this.businessType,
        RegisterCapital: this.registerCapital,
        RequirementBeginTime: this.xinjianshijian[0],
        RequirementEndTime: this.xinjianshijian[1],
        PageIndex: this.PageIndex,
        PageSize: this.PageSize
      }).then(res => {
        this.loading = false
        if (res.data.success) {
          this.listData = res.data.data
          this.codeTotal = res.data.totalRows
          this.transRate = res.data.extraInfo.transRate.toFixed(2)
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    openCreateModal (customerId, requirementId, name) {
      this.requirementName = name
      this.requirementId = requirementId
      this.customerId = customerId
      this.createModal = true
    },
    // 查询
    searchBtn () {
      this.PageIndex = 1
      this.getList()
    },
    // 客户导入
    importBtn () {

    },
    // 添加方案
    handleSubmit (name) {
      console.log('^^^^^^^^^')
      this.$refs[name].validate((valid) => {
        console.log('@@@@@@@@@@@@')
        if (valid) {
          console.log('############')
          if (this.fileArr.length > 0) {
            let formData = new FormData()
            formData.append('signTime', this.formValidate.signTime)
            formData.append('amt', this.formValidate.amt)
            formData.append('startDate', this.formValidate.startDate)
            formData.append('endDate', this.formValidate.endDate)
            formData.append('duration', this.formValidate.duration)
            formData.append('invoiceAmt', this.formValidate.invoiceAmt)
            formData.append('invoiceTime', this.formValidate.invoiceTime)
            formData.append('completeTime', this.formValidate.completeTime)

            formData.append('customerId', this.customerId)
            formData.append('requirementId', this.requirementId)
            this.fileArr.forEach(item => {
              formData.append('atta', item)
            })

            HRDCCustomerApi.PostSalesContract(formData).then((res) => {
              if (res.data.success) {
                this.$Message.success(res.data.message)

                this.createModal = false
                this.fileArr = []
                this.formValidate = {
                  signTime: '', // 签约时间
                  amt: '', // 金额
                  // code: '', // 合同编号
                  startDate: '', // 开始时间
                  endDate: '', // 结束时间
                  duration: '', // 合同年限
                  invoiceAmt: '', // 开票金额
                  invoiceTime: '', // 开票时间
                  completeTime: this.$moment(new Date()).format('YYYY-MM-DD HH:mm')
                }
                this.$refs[name].resetFields()
              } else {
                
                this.$Message.error({
                  content: res.data.message,
                  duration: 10,
                  closable: true
                })
              }
            })
          } else {
            this.hasFile = true
          }
        } else {
          this.$Message.warning('有必填项未填!')
        }
      })
    },
    // 上传方案附件
    createHandleUpload (file) {
      this.fileArr.push(file)
      this.hasFile = false
      console.log(this.fileArr)
      return false
    },
    deleteFile (index) {
      this.fileArr.splice(index, 1)
    },
    signTimeChange (val) {
      this.formValidate.signTime = val
    },
    startDateChange (val) {
      this.formValidate.startDate = val
    },
    endDateChange (val) {
      this.formValidate.endDate = val
    },
    invoiceTimeChange (val) {
      this.formValidate.invoiceTime = val
    },
    completeTimeChange (val) {
      this.formValidate.completeTime = val
    },
    tableSelectChange () {

    },
    pageChangeFn (val) {
      this.PageIndex = val
      this.getList()
    },
    onpageSizeChange (val) {
      this.PageSize = val
      this.getList()
    },

    handleShowCloseModal(row) {
      this.$refs.CloseModal.show(row)
      this.$refs.CloseModal.modalType = 'C'
    },

    // 客户导出
    exportBtn () {
      HRDCCustomerApi.exportBargain({
        selectedIds: this.ids,
        name: this.name,
        salerName: this.salerName,
        HolderIds: this.salesIds,
        Character: this.character,
        Size: this.size,
        Status: this.status,
        BusinessType: this.businessType,
        RegisterCapital: this.registerCapital,
        RequirementBeginTime: this.xinjianshijian[0],
        RequirementEndTime: this.xinjianshijian[1],
      }).then(res => {
        if (res.data.success) {
          let objectUrl = res.data.data
          console.log(objectUrl)
          const link = document.createElement('a')
          link.download = ''
          link.href = objectUrl
          link.click()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },

    timeChange (event) {
      console.log('时间改变 event: ', event)
      this.xinjianshijian = event
    }
  }
}
</script>

<style>

</style>
